﻿namespace HZY.Core.Filters;

/// <summary>
/// Api 结果返回包装器
/// </summary>
public class ApiResultFilterAttribute : Attribute, IAsyncResultFilter
{
    public bool Ignore { get; set; }

    public ApiResultFilterAttribute(bool ignore = false)
    {
        Ignore = ignore;
    }

    /// <summary>
    /// 结果 返回前
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        if (!Ignore && context.Result != null && !context.HttpContext.IsDownLoadFile())
        {
            if (context.Result is ObjectResult)
            {
                var result = context.Result as ObjectResult;
                context.Result = new JsonResult(R.Ok("success", result?.Value));
            }
            else if (context.Result is ContentResult)
            {
                var result = context.Result as ContentResult;
                context.Result = new JsonResult(R.Ok("success", result?.Content));
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new JsonResult(R.Ok("success", null));
            }
        }

        // Continue execution in the pipeline
        await next.Invoke();
    }

}